package scr.springbootcaffeineredis;

import com.github.benmanes.caffeine.cache.Cache;
import io.lettuce.core.RedisClient;
import io.lettuce.core.TrackingArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.support.caching.CacheFrontend;
import io.lettuce.core.support.caching.ClientSideCaching;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class CacheFrontendContext {
    private RedisClient redisClient;
    private Cache cache;

    public CacheFrontendContext(RedisClient redisClient, Cache cache) {
        this.redisClient = redisClient;
        this.cache = cache;

    }

    @Getter
    private CacheFrontend cacheFrontend;
    StatefulRedisConnection<String, String> connection;


    public void check() {
        if (connection != null) {
            if (connection.isOpen()) {
                return;
            }
        }
        try {
            connection = redisClient.connect();
            CacheFrontend<String, String> frontend =
                    ClientSideCaching.enable(new CaffeineCacheAccessor(cache), connection, TrackingArgs.Builder.enabled().noloop());
            this.cacheFrontend = frontend;
            connection.addListener(message -> {
                List<Object> content = message.getContent(StringCodec.UTF8::decodeKey);
                log.info("type:{},content:{}", message.getType(), message.getContent());
                if ("invalidate".equals(message.getType())) {
                    List<String> keys = (List<String>) content.get(1);
                    keys.forEach(key -> {
                        cache.invalidate(key);
                    });
                }

            });

            log.warn("The redis client side connection had been reconnected");
        } catch (Exception e) {

            e.printStackTrace();

            log.error("The redis client side connection had been disconnected,waiting reconnect...");
        }

    }


}
